import { defineStore } from 'pinia'
import { ref } from 'vue'
import { showToast } from 'vant'
import {
  getRecycleFileList,
  restoreFile,
  permanentDeleteFile,
  clearRecycleBin,
  type FileListParams,
  type FileInfo
} from '@/api/file'

export const useRecycleStore = defineStore('recycle', () => {
  const recycleList = ref<FileInfo[]>([])
  const loading = ref<boolean>(false)
  const pagination = ref({
    total: 0,
    page: 1,
    size: 20,
    pages: 0
  })

  const fetchRecycleList = async (params?: Partial<FileListParams>) => {
    try {
      loading.value = true

      const requestParams: FileListParams = {
        page: pagination.value.page,
        size: pagination.value.size,
        orderBy: 'updateTime',
        orderType: 'desc',
        ...params
      }

      const response = await getRecycleFileList(requestParams)

      recycleList.value = response.content
      pagination.value = {
        total: response.totalElements || response.total || 0,
        page: (response.number !== undefined ? response.number + 1 : response.page) || 1,
        size: response.size || 20,
        pages: response.totalPages || response.pages || 1
      }

      return response
    } catch (error) {
      console.error('获取回收站列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  const restoreFileItem = async (fileId: number) => {
    try {
      await restoreFile(fileId)
      showToast({
        type: 'success',
        message: '文件已恢复'
      })
      await fetchRecycleList()
    } catch (error) {
      console.error('恢复文件失败:', error)
      throw error
    }
  }

  const deleteFileForever = async (fileId: number) => {
    try {
      await permanentDeleteFile(fileId)
      showToast({
        type: 'success',
        message: '文件已彻底删除'
      })
      await fetchRecycleList()
    } catch (error) {
      console.error('彻底删除文件失败:', error)
      throw error
    }
  }

  const clearAll = async () => {
    try {
      await clearRecycleBin()
      showToast({
        type: 'success',
        message: '回收站已清空'
      })
      await fetchRecycleList()
    } catch (error) {
      console.error('清空回收站失败:', error)
      throw error
    }
  }

  const refreshRecycleList = () => {
    return fetchRecycleList()
  }

  const resetState = () => {
    recycleList.value = []
    pagination.value = {
      total: 0,
      page: 1,
      size: 20,
      pages: 0
    }
  }

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'

    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  const formatTime = (time: string): string => {
    return new Date(time).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  return {
    recycleList,
    loading,
    pagination,

    fetchRecycleList,
    restoreFileItem,
    deleteFileForever,
    clearAll,
    refreshRecycleList,
    resetState,
    formatFileSize,
    formatTime
  }
})